#include<stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define N 10
void RunChild()
{
    int cnt = 5;
    while(cnt)
    {
        printf("I am Child Process, pid: %d, ppid:%d\n", getpid(), getppid());
        sleep(1);
        cnt--;
    }
}
int main()
{
  /*for(int i=0;i<N;i++)
  {
    pid_t id = fork();
    if(id == 0)
    {
      RunChild();
      exit(i);
    }
    printf("Creat Child Process: %d Success\n",id);
  }
  return 0;*/
  pid_t id = fork();
  if(id < 0)
  {
    perror("fork");
    return 1;
  }
  else if (id ==0)
  {
    int cnt =5;
    while(cnt)
    {
      printf("I am child,pid:%d,ppid:%d,cnt:%d\n",getpid(),getppid(),cnt);
      cnt--;
      sleep(1);
    }
    exit(11);
  }
  else{
   /* int cnt = 5;
     while(cnt)
     {
          printf("I am father, pid:%d, ppid:%d, cnt: %d\n", getpid(), getppid(), cnt);
          cnt--;
          sleep(1);
     }*/ 
    int status = 0;
    while(1)
    {
      pid_t ret = waitpid(id, &status, WNOHANG); //非阻塞
      if(ret > 0)
      {
        if(WIFEXITED(status))
        {
          printf("进程是正常跑完的，退出码为：%d\n",WEXITSTATUS(status));
        }
        else 
        {
          printf("进程异常退出了。\n");
        }
        break;
      }
      else if(ret <0)
      {
        printf("wait failed\n");
        break;
      }
      else{
        printf("你好了没？子进程还没有退出，我在等等...\n");
        sleep(1);
      
      }

    }
  }
  return 0;
}

